package cn.xorange.commons.utils.ip;

import cn.hutool.http.HttpUtil;
import cn.xorange.commons.utils.lang.ObjectUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取地址类
 * 
 * @author ruoyi
 */
@Slf4j
public class AddressUtils
{
    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "XX XX";

    public static String getRealAddressByIP(String ip)
    {
        String address = UNKNOWN;
        // 内网不查询
        if (IpUtils.internalIp(ip))
        {
            return "内网IP";
        }
        try
        {
            Map<String,Object> params = new HashMap<>(2);
            params.put("ip",ip);
            params.put("json",true);
            //HttpUtil.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
            String rspStr = HttpUtil.get(IP_URL,params);
            if (rspStr.isEmpty())
            {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            JSONObject obj = JSON.parseObject(rspStr);
            String region = ObjectUtils.toString(obj.get("pro"));
            String city = ObjectUtils.toString(obj.get("city"));
            return String.format("%s %s", region, city);
        }
        catch (Exception e)
        {
            log.error("获取地理位置异常 {}", ip);
        }
        return address;
    }
}
